/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package manager;

import java.util.List;
import java.util.PriorityQueue;
import model.Event;
import model.Packet;

/**
 *
 * @author wpc
 */
public class EventManager {

    private PriorityQueue<Event> queue;
    private PacketGeneratorManager gm;
    private QueueManager qm;

    public EventManager(PacketGeneratorManager gm, QueueManager qm) {
        this.gm = gm;
        this.qm = qm;
        queue = new PriorityQueue<Event>();
    }

    public void run(){
        while(true){
            //No new Event
            if(queue.isEmpty()){
              List<Packet> newPacketList = gm.next();
              if(newPacketList==null){
                  break;
              }
              addNewPackets(newPacketList);
            }
            Event e = queue.poll();
            if(e.isArrival()){
                arrivalEvent(e);
            }else{
                departureEvent(e);
            }
        }
    }

    private void addNewPackets(List<Packet> packetList){
        for(Packet packet:packetList){
            addArrivalEvent(packet);
        }
    }

    private void arrivalEvent(Event e){
        Packet packet = e.getPacket();
        if(!qm.isLoss(packet)){
            addDepartureEvent(packet);
        }
        addNewPackets(gm.next(packet.getFinish()));
    }

    private void addDepartureEvent(Packet p){
        this.queue.add(new Event(false, p));
    }

    private void departureEvent(Event e){
        Packet packet = e.getPacket();
        if(qm.departure(packet))
            return;
        addArrivalEvent(packet);
    }

    private void addArrivalEvent(Packet p){
        this.queue.add(new Event(p));
    }
}
